<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-7-23
 * Time: 上午11:29
 */

namespace Admin\Controller;

use Common\Controller\AdminCommonController;

/**
 * 自动任务控制器
 * Class CrontabController
 * @package Admin\Controller
 */
class CrontabController extends AdminCommonController
{
    private $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = D('Crontab');
    }

    /**
     * 计划任务基本配置
     */
    public function index()
    {
        $list = $this->model->getList();
        $this->assign($list);
        $this->display();
    }

    /**
     * 编辑与添加页面
     */
    public function edit()
    {
        $id = I('get.id');

        if ($id) {
            $detail = $this->model->getConfigDetail($id);
            $this->assign($detail);
        }

        $this->display();
    }


    public function update()
    {
        if (!IS_AJAX) {
            toErrorPage();
            exit;
        }

        $id = I('post.id');
        $data['name'] = I('post.name');
        $data['model'] = I('post.model');
        $data['method'] = I('post.method');
        $data['cycle'] = I('post.cycle');
        $res = $this->model->update($id,$data);
        $title = empty($id) ? '添加' : '保存';
        if ($res || $res===0) {
            $this->addHistoryLog($title . '任务计划配置成功！');
            $this->returnData($title . '成功', 1);
        } else {
            $this->addHistoryLog($title . '任务计划配置失败！');
            $this->returnData($title . '失败');
        }
    }

    public function setStatus()
    {
        if (!IS_AJAX) {
            toErrorPage();
            exit;
        }

        $id = I('post.id');
        $status = I('post.status', '', 'intval') == 1 ? 0 : 1;

        if (empty($id)) {
            $this->returnData('请选择操作项');
        }

        $res = $this->model->setStatus($id, $status);

        if ($res)
        {
            $this->addHistoryLog('更新任务计划配置状态成功！');
            $this->returnData('操作成功', 1);
        } else {
            $this->addHistoryLog('更新任务计划配置状态失败！');
            $this->returnData('操作失败');
        }
    }

    /**
     * 删除任务计划配置
     */
    public function delCrontabConfig()
    {
        if (!IS_AJAX) {
            toErrorPage();
            exit;
        }
        $id = I('post.id');

        if (empty($id)) {
            $this->returnData('请选择操作项');
        }

        $res = D('Crontab')->delete($id);

        if ($res) {
            $this->addHistoryLog('删除任务计划配置成功！');
            $this->returnData('删除成功', 1);
        } else {
            $this->addHistoryLog('删除任务计划配置失败！');
            $this->returnData('删除失败');
        }
    }
}